package com.ustc.jsondb;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.log4j.Logger;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;

import com.google.gson.Gson;

/**
 * jsonDb
 * @author Administrator
 *
 */
public class JsonDb {

	private Logger logger = Logger.getLogger(JsonDb.class);
	
	private static final String _uuid = "_uuid";
	
	public void createDb(String path) throws Exception{
		
		OutputStream os = new FileOutputStream(path);
		
		Document db = new Document();
		
		Element root = new Element("databse");
		
		Element table1 = new Element("table");
		table1.setAttribute("name","test");
		
		Element table2 = new Element("table");
		table2.setAttribute("name","system.index");
		
		Element table3 = new Element("table");
		table3.setAttribute("name","system.user");
		
		root.addContent(table1);
		root.addContent(table2);
		root.addContent(table3);
		
		db.setRootElement(root);
		
		XMLOutputter out = new XMLOutputter();
		out.output(db, os);
		
		logger.debug("db create success!");
	}
	
	/**
	 * 添加数据
	 */
	public void addData(String path,String tableName,Object data) throws Exception{
		
		Gson gson = new Gson();
		FileInputStream in= new FileInputStream(path);
		SAXBuilder sax = new SAXBuilder();
		Document document = sax.build(in);
		Element root = document.getRootElement();
		
		List<Element> childrens = root.getChildren();
		for(Element e:childrens){
			if(e.getAttributeValue("name").equals(tableName)){
				Map<String, Object> map = new HashMap<String, Object>();
				Element dataElement = new Element("data");
				map.put(_uuid, UUID.randomUUID().toString());
				Map mp = gson.fromJson(gson.toJson(data), Map.class);
				map.putAll(mp);
				dataElement.addContent(gson.toJson(map));
				e.addContent(dataElement);
				
				
				
			}
			
		}
		
		XMLOutputter out = new XMLOutputter();
		out.output(document,  new FileOutputStream(path));
		
		logger.debug("db add data success!");
		
	}
	
	/**
	 * 更新数据
	 */
	public void updateData(String path,String tableName,Object o) throws Exception{
		Gson gson = new Gson();
		FileInputStream in= new FileInputStream(path);
		SAXBuilder sax = new SAXBuilder();
		Document document = sax.build(in);
		Element root = document.getRootElement();
		
		List<Element> childrens = root.getChildren();
		for(Element e:childrens){
			if(e.getAttributeValue("name").equals(tableName)){
				
				List<Element> list = e.getChildren();
				for(Element el:list){
					Map oldJson = gson.fromJson(el.getText(), Map.class);
					
					Map newJson = gson.fromJson(gson.toJson(o), Map.class);
					
					if(oldJson.get("_id").equals(newJson.get("_id"))){
						oldJson.putAll(newJson);
						Element data = new Element("data");
						
						data.setText(gson.toJson(oldJson));
						el.removeContent(el);
						el.addContent(data);
					}
				}
				
				/*Map<String, Object> map = new HashMap<String, Object>();
				Element dataElement = new Element("data");
				map.put(_uuid, UUID.randomUUID().toString());
				Map mp = gson.fromJson(gson.toJson(data), Map.class);
				map.putAll(mp);
				dataElement.addContent(gson.toJson(map));
				e.addContent(dataElement);*/
				
				
				
			}
			
		}
		
		XMLOutputter out = new XMLOutputter();
		out.output(document,  new FileOutputStream(path));
		
		logger.debug("db update data success!");
	}
	
	/**
	 * 删除数据
	 */
	public void deleteData(String path,String tableName,Object o) throws Exception{
		Gson gson=new Gson();
		
		FileInputStream input=new FileInputStream(path);
		SAXBuilder saxBuilder=new SAXBuilder();
		Document document=saxBuilder.build(input);
		Element root=document.getRootElement();
		
		List<Element> list=root.getChildren();
		for(Element e:list){
			if(e.getAttributeValue("name").equals(tableName)){
				List<Element> datas=e.getChildren();
				for(Element s:datas){
					Map old=gson.fromJson(s.getText(), Map.class);
					Map newData=gson.fromJson(gson.toJson(o),Map.class);
					if(old.get("_id").equals(newData.get("_id"))){
						e.removeContent(s);
						break;
					}
				}
			}
			
		}
		XMLOutputter outputter=new XMLOutputter();
		
		outputter.output(document,new FileOutputStream(path));

		logger.debug("db delete data success!");
	}
	
	/**
	 * 查询数据
	 */
	public List<Map<String, Object>> queryData(String path,String tableName) throws Exception{
		List<Map<String, Object>> result = new ArrayList<Map<String,Object>>();
		Gson gson = new Gson();
		FileInputStream input=new FileInputStream(path);
		SAXBuilder saxBuilder=new SAXBuilder();
		Document document=saxBuilder.build(input);
		Element root=document.getRootElement();
		
		List<Element> list=root.getChildren();
		for(Element e:list){
			if(e.getAttributeValue("name").equals(tableName)){
				List<Element> datas=e.getChildren();
				for(Element s:datas){
					Map data = gson.fromJson(s.getText(), Map.class);
					result.add(data);
				}
			}
			
		}
		
		return result;
		
	}
	
	
}
